import { useMemo, useState } from 'react';
import { ILoadMapTypeAll } from '@/common';
import { Button, message, Space } from 'antd';
import { addTransactorService, verifyRevocaService } from '../services';
import { WorkFlowHandModal } from '../../WorkflowCheckModal';
import { WorkFlowHandNodeModal } from './WorkFlowHandNodeModal';
import { SelectUserFormModal } from '@/components/SelectUserFormModal';
import { getKeyRouter, getPosIDs, getTenantID, getUserID, isRevocationBtn } from '@/utils';
import { RevokeModal } from '@/pages/PurchaseManage/Acomponents/RevokeModal';

export const WorkflowHndTaskBtn: React.FC<IWorkflowChedkRecordAPI.IWorkflowHndTaskBtn> = ({
  flowDetailInfo,
  flowBusinessType,
  requestController,
  detailInfoObj = {},
  isAloneSubmit = false,
  applyHeader, // 当前申请头部字符串  own || apply
  revokeRequestUrl, // 当前按钮撤销接口
  revokeRequestState, // 撤销后改变的工作流状态
  isShowRevokeStateList, //在这个集合中的状态就会显示撤销
  revokeTitle, // 撤销弹窗内容
  revokeSuccessCallback, //撤销成功之后的处理，跟办理成功不一样，因为撤销后需要回到编辑页面
  revokeReqBody = {},
  reloadCallback,
  clickBeforeFun = null, // Promise 返回结果 后才会执行 async 函数后面剩下的语句，也就是说如果 Promise 不返回结果（如 resolve 或 reject），后面的代码就不会执行
  clickSuccessFun = null,
  revokeDealNum,

  // handHelpType = false, // true:帮办  false:办理 默认
  // pageHeight = 0.4,
  // isShowDrawer
}) => {
  /**
   * 按钮顺序编码集合
   * */
  const btnMapList = [
    `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1000`, //同意
    `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1003`, //提交
    `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1001`, //不同意
    // `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1002`, //退回 [暂时注释]
    `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1004`, //作废
    // `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1005`, //撤回 [当前办理人不渲染撤回按钮]
  ];

  /**
   * 否定按钮编码集合
   * */
  const btnMapNoList = [
    `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1001`, //不同意
    `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1004`, //作废
  ];

  /**判断字符串是否是纯数字 */
  const isNumeric = (str: string) => /^\d+$/.test(str);
  /** 给办理弹窗的数据 */
  const [handleBtnList, setHandleBtnList] = useState<Record<string, any>[]>([]);
  /** 打开流程指定任务节点弹框 */
  const [flowTaskNodeModal, setFlowTaskNodeModal] = useState<Record<string, any>>({ isShow: false });
  /** 保存跳转任务节点 */
  const [handTaskNodeList, setHandTaskNodeList] = useState<Record<string, any>[]>([]);
  /** 打开加签选择人员弹窗 */
  const [counterModal, setCounterModal] = useState<Record<string, any>>({});
  /** 打开流程办理弹框 */
  const [flowHandModal, setFlowHandModal] = useState<Record<string, any>>({ isShow: false, checkFlowItem: {} });
  /** 保存撤回按钮信息 */
  const [revocaInfo, setRevocaInfo] = useState<Record<string, any> | null>({});
  /** 是否是会签办理，需要的信息 */
  const [isCounterObj, setIsCounterObj] = useState<Record<string, any>>({});
  /** 保存当前办理人节点 */
  const [completeUserObj, setCompleteUserObj] = useState<Record<string, any>>({});
  /** 是否可以撤回 */
  const [isShowRevoa, setIsShowRevoa] = useState<boolean | null>(null);
  /** 撤销弹窗 */
  const [revokeState, setRevokeState] = useState<boolean | null>(false);

  /** 校验是否可以办理接口 */
  const { verifyRevocaRun, verifyRevocaLoading } = verifyRevocaService((res) => {
    setIsShowRevoa(res?.msgFlag);
  }, 'activitiController');

  /** 加签接口 */
  const { addTransactorRun, addTransactorLoading } = addTransactorService((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      reloadCallback();
    }
  }, requestController);

  /** 处理详情数据 - 判断办理节点是否是当前人 - 是的话则返回操作按钮 */
  const renderBtn = useMemo(() => {
    let taskList = flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiTaskList;
    if (flowDetailInfo?.id && taskList) {
      let taskNode = taskList?.find((item) => item?.assigneeID == getUserID() && item?.assigneePositionID == getPosIDs());
      /** 判断是否是当前办理人 */
      if (taskNode) {
        setCompleteUserObj(taskNode);

        let arr: any = [];
        let nodeList: Record<string, any>[] = []; //存储流程任务节点
        let taskBtnType: boolean = false; //判断是否有跳转节点

        /**对按钮排序，挑出是否有跳转节点【不太理解，照搬的代码】*/
        taskNode?.msequenceFlowList?.forEach((item) => {
          if (isNumeric(item?.flowValue)) {
            const indexs = btnMapList?.findIndex((items) => items === item?.flowValue);
            arr[indexs] = item;
          } else {
            taskBtnType = true;
            nodeList?.push(item);
          }
        });
        setHandTaskNodeList(nodeList);

        /**排序后数组可能会有为空的项，把他们剔除*/
        let result: Record<string, any>[] | any = arr?.filter((item) => item != null);

        /**isAloneSubmit 为true 则只留第一个办理按钮*/
        if (isAloneSubmit) {
          result = [result[0]];
        }

        /**是否有跳转节点*/
        if (taskBtnType) {
          result?.push({
            flowID: `jumpBtn-${getKeyRouter()}`,
            flowName: '跳转',
            flowValue: '跳转',
            btnType: true,
          });
          taskBtnType = false;
        }

        setHandleBtnList(result); //打开流程办理弹窗使用

        return result;
      }
    } else {
      return [];
    }
  }, [flowDetailInfo, flowBusinessType, flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiTaskList]);

  /** 是否展示撤回按钮 */
  const isShowRevoaBtnMemo = useMemo(() => {
    let result = isRevocationBtn(flowDetailInfo, flowBusinessType);
    // 为false就直接返回
    if (!result) return result;
    let { revocainfo, handlebtnlist, completeuserobj, iscounterobj }: Record<string, any> = result;
    // console.log("======================>>>>>dayin", revocainfo, handlebtnlist, completeuserobj, iscounterobj)
    // 保存撤回按钮对象 | 如果无撤回按钮则方法[isRevocationBtn]直接返回false
    if (revocainfo) setRevocaInfo(revocainfo);
    // 保存当前任务节点身上的操作按钮数组
    if (handlebtnlist) setHandleBtnList(handlebtnlist);
    // 保存当前任务节点对象
    if (completeuserobj) setCompleteUserObj(completeuserobj);
    /**
     * 保存对象 3个值
     * [taskIsSign = 1 说明上个任务是会签]
     * [taskList 保存的是当前任务集合]
     * [isCurrent true:当前节点是普通节点,上一个节点是会签节点 false:当前是会签节点，上一个也是会签节点]
     * */
    if (iscounterobj) setIsCounterObj(iscounterobj);

    if (iscounterobj?.taskIsSign === 1) {
      if (isShowRevoa === null) {
        verifyRevocaRun({
          id: iscounterobj?.taskList?.map((item) => item.id)?.join(','),
          orderID: iscounterobj?.taskList[0]?.orderID,
        });
      } else {
        return isShowRevoa;
      }
    } else {
      return result;
    }
  }, [flowDetailInfo, flowBusinessType, flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiTaskList?.[0]?.taskDefKey, isShowRevoa]);

  /** 是否展示加签按钮 */
  const isShowAddUserMemo = useMemo(() => {
    let taskList = flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiTaskList;
    if (taskList && taskList?.length >= 1 && taskList?.[0]?.taskIsSign == 1) {
      return taskList?.find((item) => item?.assigneeID == getUserID() && item?.assigneePositionID == getPosIDs());
    }
    return false;
  }, [flowDetailInfo, flowBusinessType]);

  /** 是否展示撤销按钮 */
  const isRevokeBtnMemo = useMemo(() => {
    if (
      revokeRequestUrl &&
      revokeRequestState &&
      isShowRevokeStateList?.length &&
      flowDetailInfo?.id &&
      flowDetailInfo[`${applyHeader}erID`] == getUserID() &&
      flowDetailInfo[`${applyHeader}PositionID`] == getPosIDs() &&
      isShowRevokeStateList?.indexOf(flowDetailInfo?.state) !== -1
      // (flowDetailInfo?.state == `${revokeRequestState}1001` || flowDetailInfo?.state == `${revokeRequestState}1000`)
    ) {
      return true;
    } else {
      return false;
    }
  }, [flowDetailInfo, flowBusinessType, revokeRequestState, isShowRevokeStateList]);

  return (
    <>
      <Space>
        {/* 同意不同意按钮 */}
        {renderBtn?.map((item: any) => {
          /**
           * 找到否定的按钮
           * */
          let dangerBool: boolean = false;
          if (btnMapNoList?.includes(item?.flowValue)) {
            dangerBool = true;
          }
          /**
           * 渲染使用
           * */
          const [flowText, _flowColor] = item?.flowName?.split('||');
          return (
            <Button
              type="primary"
              // icon={item?.btnType ? <NodeExpandOutlined /> : dangerBool ? <CloseCircleOutlined /> : <CheckCircleOutlined />}
              danger={dangerBool}
              key={item?.flowID}
              onClick={async () => {
                if (item?.btnType) {
                  //处理点击跳转逻辑
                  setFlowTaskNodeModal({ isShow: true });
                } else {
                  if (clickBeforeFun) {
                    await clickBeforeFun();
                  }
                  setFlowHandModal({
                    isShow: true,
                    checkFlowItem: { ...item, flowText: flowText },
                  });
                }
              }}
            >
              {flowText}
            </Button>
          );
        })}

        {/* 加签按钮 */}
        {isShowAddUserMemo && (
          <Button
            type="primary"
            // icon={<UserAddOutlined />}
            onClick={() => setCounterModal({ isShow: true })}
          >
            加签
          </Button>
        )}

        {/* 撤回按钮 */}
        {isShowRevoaBtnMemo && (
          <Button
            danger
            // icon={<RetweetOutlined />}
            type="primary"
            onClick={() => {
              /**判断是否可以办理*/
              let taskList = flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiTaskList;
              if (taskList && taskList?.length) {
                let ids = '';
                /**普通任务*/
                if (taskList?.length == 1 && taskList?.[0]?.taskIsSign == 0) ids = taskList?.[0]?.id;
                /**会签任务*/
                if (taskList?.length >= 1 && taskList?.[0]?.taskIsSign == 1) ids = taskList?.map((item) => item.id)?.join(',');

                verifyRevocaRun({ id: ids, orderID: taskList[0]?.orderID })?.then((res) => {
                  if (res?.msgFlag) {
                    let flowText = revocaInfo?.flowName?.split('||')?.[0];
                    setFlowHandModal({
                      isShow: true,
                      checkFlowItem: { ...revocaInfo, flowText: flowText },
                    });
                  } else {
                    message?.warn(res?.msg);
                    reloadCallback();
                  }
                });
              }
            }}
          >
            撤回
          </Button>
        )}

        {/* 撤销按钮 */}
        {isRevokeBtnMemo && (
          <Button
            type="primary"
            danger
            // icon={<RollbackOutlined />}
            onClick={() => setRevokeState(true)}
          >
            撤销
          </Button>
        )}
      </Space>

      {/* 打开流程办理弹框 */}
      {flowHandModal?.isShow && (
        <WorkFlowHandModal
          onClose={() => {
            setFlowHandModal({
              isShow: false,
              checkFlowItem: {},
            });
          }}
          checkItemObj={flowHandModal?.checkFlowItem}
          reloadCallback={() => {
            setIsCounterObj({});
            reloadCallback();
            if (clickSuccessFun) {
              clickSuccessFun();
            }
            setIsShowRevoa(null);
          }}
          flowDetailInfo={completeUserObj}
          requestController={requestController}
          checkflowList={handleBtnList}
          detailInfoObj={detailInfoObj}
          isCounterObj={isCounterObj}
        />
      )}

      {/* 跳转任务弹框 */}
      {flowTaskNodeModal?.isShow && (
        <WorkFlowHandNodeModal
          onClose={() => {
            setFlowTaskNodeModal({
              isShow: false,
            });
          }}
          handTaskNodeList={handTaskNodeList}
          reloadCallback={reloadCallback}
          flowDetailInfo={completeUserObj}
          requestController={requestController}
        />
      )}

      {/* 加签选择岗位人组件 */}
      {counterModal?.isShow && (
        <SelectUserFormModal
          onSelect={(res) => {
            let { CompanDeptPos, UserID } = res;
            if (CompanDeptPos && UserID) {
              addTransactorRun({
                ...completeUserObj,
                assigneeID: UserID,
                assigneePositionID: CompanDeptPos,
              });
            }
          }}
          onClose={() => setCounterModal({})}
          loading={addTransactorLoading}
        />
      )}

      {/* 撤销弹窗 */}
      {revokeState && (
        <RevokeModal
          resObj={flowDetailInfo}
          revokeRequestUrl={revokeRequestUrl}
          onClose={() => setRevokeState(false)}
          reqBody={{ id: flowDetailInfo?.id, state: `${revokeRequestState}1000`, ...revokeReqBody }}
          modalTip={
            <div style={{ color: '#000' }}>
              确认是否撤销【<span style={{ color: 'red' }}>{revokeTitle || flowDetailInfo?.createrName}</span>】的审核, 撤销后可重新提交！
            </div>
          }
          reloadRequest={async () => {
            // 撤销弹窗  取消物资的锁定
            if (revokeDealNum) {
              await revokeDealNum();
            }
            if (revokeSuccessCallback) {
              revokeSuccessCallback();
            }
          }}
        />
      )}
    </>
  );
};

/**
 * 撤回按钮编码
 * */
// const backButtonVal = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1005`;

/**
 * 审核中-流程状态
 * */
// const AuditState = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000`;

/**
 * 编制中-流程状态
 * */
// const WeaveState = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1001`;

/** 是否展示撤回按钮 */
// const isShowRevoaBtnMemo = useMemo(() => {
//   /** 当前办理任务信息 */
//   let taskList: Record<string, any>[] | null = flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiTaskList;
//   /**历史办理任务信息*/
//   let localTaskList: Record<string, any>[] | null = flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
//   /**流程当前状态*/
//   let taskCheckState: string | null = flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiHisProcinstList?.[0]?.checkResult;

//   /**
//    * 判断详情和任务列表
//    * */
//   if (flowDetailInfo?.id && taskList) {
//     // debugger;
//     // 普通任务
//     if (taskList?.length == 1 && taskList?.[0]?.taskIsSign == 0) {
//       const taskNode = taskList?.[0];
//       setCompleteUserObj(taskNode);
//       const transacBtnList = taskNode?.msequenceFlowList;
//       // 首先先确定按钮列表中是否有撤回按钮
//       const isThereBtn = transacBtnList?.find((item) => item?.flowValue == backButtonVal);
//       // 如果没有撤回按钮，直接return false
//       if (!isThereBtn) return false;
//       // 如果有，那么去历史办理节点找第二个【上一个人】
//       if (localTaskList && localTaskList?.length >= 2 && (taskCheckState == AuditState || taskCheckState == WeaveState)) {
//         const preNode = localTaskList?.[1];
//         if (preNode?.taskIsSign == 0) {
//           //上一个节点是普通任务
//           if (preNode?.assigneeID == getUserID() && preNode?.assigneePositionID == getPosIDs()) {
//             setRevocaInfo(isThereBtn); //保存撤回按钮信息
//             setHandleBtnList(transacBtnList); //保存应办人的按钮列表
//             return true;
//           }
//         } else if (preNode?.taskIsSign == 1) {
//           if (preNode?.comment != '撤回') {
//             //上一个节点是会签任务
//             const taskKey = preNode?.taskDefKey;
//             const counterLocalTaskList = localTaskList?.filter((item) => item?.taskDefKey == taskKey);
//             const flagObj = counterLocalTaskList?.find((item) => item?.assigneeID == getUserID() && item?.assigneePositionID == getPosIDs());
//             if (flagObj) {
//               setRevocaInfo(isThereBtn); //保存撤回按钮信息
//               setHandleBtnList(transacBtnList); //保存应办人的按钮列表
//               setIsCounterObj({ taskIsSign: 1, taskList: counterLocalTaskList, isCurrent: true }); //标识是会签批量操作
//               return true;
//             }
//           }
//         }
//       } else {
//         return false;
//       }
//     }
//     // 会签任务
//     if (taskList?.length >= 1 && taskList?.[0]?.taskIsSign == 1) {
//       // 从历史任务中找数据【条件1：是会签任务，条件2：未办理】（流程中的节点，如果有会签，要么是已经办过的，要么是后面的，后面的还不会存在在历史节点信息里）
//       const taskKey = taskList[0].taskDefKey;
//       const transacBtnList = taskList[0]?.msequenceFlowList;
//       const localCounterTaskList = localTaskList?.filter((item) => item?.taskIsSign == 1 && taskKey == item?.taskDefKey && !item?.comment);
//       const isThereBtn = transacBtnList?.find((item) => item?.flowValue == backButtonVal);
//       const preNode = localTaskList?.find((item) => item?.taskDefKey != taskKey);
//       if (
//         localCounterTaskList?.length === taskList?.length &&
//         isThereBtn &&
//         preNode?.assigneeID == getUserID() &&
//         preNode?.assigneePositionID == getPosIDs() &&
//         preNode?.comment != '撤回'
//       ) {
//         // 说明会签任务，一个都没有办理
//         setRevocaInfo(isThereBtn); //保存撤回按钮信息
//         setHandleBtnList(transacBtnList); //保存应办人的按钮列表
//         setIsCounterObj({ taskIsSign: 1, taskList, isCurrent: false }); //标识是会签批量操作
//         return true;
//       }
//     }
//   }
//   return false;
// }, [flowDetailInfo, flowBusinessType, flowDetailInfo?.paramObject?.[flowBusinessType]?.mactivitiTaskList?.[0]?.taskDefKey]);
